import logo from "./logo.svg";
import "./App.css";
import React, { useState, useEffect } from "react";
import Header from "./components/Header";
import Tasks from "./components/Tasks";
import AddTask from "./components/AddTask";
import Footer from "./components/Footer";
import About from "./components/About";
import { BrowserRouter as Router, Route } from "react-router-dom";

function App() {
  const [tasks, setTasks] = useState([]);
  const [showAdd, setShowAdd] = useState(false);

  useEffect(() => {
    const getTask = async () => {
      const data = await fetchTask();
      setTasks(data);
    };
    getTask();
  }, []);

  const fetchTask = async () => {
    const res = await fetch("http://localhost:5000/tasks");
    const data = await res.json();
    return data;
  };

  const deleteTask = async (id) => {
    const res = await fetch(`http://localhost:5000/tasks/${id}`, {
      method: "DELETE",
    });
    const data = await res.json();
    setTasks(tasks.filter((task) => task.id !== data.id));
  };

  const addTask = (task) => {
    const id = Math.floor(Math.random() * 1000) + 1;
    const newTask = { ...task, id };
    setTasks([...tasks, newTask]);
  };

  const toggleImportant = (id) => {
    setTasks(
      tasks.map((task) =>
        task.id === id ? { ...task, important: !task.important } : task
      )
    );
  };

  return (
    <Router>
      <div className="container">
        <Header
          text="TodoList"
          showAdd={showAdd}
          onClick={() => setShowAdd(!showAdd)}
        />
        <Route
          path="/"
          exact
          render={() => (
            <>
              {showAdd && <AddTask onAdd={addTask} />}{" "}
              <Tasks
                tasks={tasks}
                onDelete={deleteTask}
                onToggle={toggleImportant}
              />
            </>
          )}
        />
        <Route path="/about" component={About} />

        <Footer />
      </div>
    </Router>
  );
}

export default App;
